/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.finance.ap.memo.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.springmvc.ControllerSupport;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.erp.common.ap.pay.service.ApPayHeadService;
import com.erp.common.voucher.service.FinVoucherBillRService;
import com.erp.common.voucher.service.FinVoucherHeadService;
import com.erp.common.voucher.service.FinVoucherModelHeadService;
import com.erp.cux.workflow.controller.CuxControllerSupport;
import com.erp.dataset.service.DatasetCommonService;
import com.erp.finance.ap.invoice.dao.model.ApInvoiceHead;
import com.erp.finance.ap.invoice.service.ApInvoiceHeadService;
import com.erp.finance.ap.memo.dao.data.DataBox;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoHead;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoHeadBase;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoHeadCO;
import com.erp.finance.ap.memo.dao.model.ApInvoiceMemoLine;
import com.erp.finance.ap.memo.service.ApInvoiceMemoHeadService;
import com.erp.finance.ap.memo.service.ApInvoiceMemoLineService;
import com.erp.finance.ap.pay.service.ApPayLineService;
import com.erp.finance.apeco.memo.service.ApInvoiceMemoEcoService;
import com.erp.finance.apeco.memo.service.ApInvoiceMemoHeadMService;
import com.erp.hr.dao.model.HrStaffInfoRO;
import com.erp.hr.service.HrCommonService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.vendor.dao.model.MdVendor;
import com.erp.masterdata.vendor.dao.model.MdVendorBank;
import com.erp.masterdata.vendor.dao.model.MdVendorBankCO;
import com.erp.masterdata.vendor.service.MdVendorBankService;
import com.erp.order.po.dao.model.PoHead;
import com.erp.order.po.dao.model.PoHeadCO;
import com.erp.order.po.service.PoHeadService;
import com.erp.order.po.service.PoLineService;

@Controller
@RequestMapping("/web/apInvoiceMemoHead")
public class ApInvoiceMemoHeadWebController extends CuxControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(ApInvoiceMemoHeadWebController.class);
    
    //服务层注入
    @Autowired
    private ApInvoiceMemoHeadService apInvoiceMemoHeadService;
    @Autowired
    private ApInvoiceMemoLineService apInvoiceMemoLineService;
    @Autowired
    private ApInvoiceHeadService apInvoiceHeadService;
    //@Autowired
    //private ApInvoiceLineService apInvoiceLineService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private HrCommonService hrCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private MdVendorBankService mdVendorBankService;
    @Autowired
    private PoHeadService poHeadService;
    @Autowired
    private PoLineService poLineService;
    @Autowired
    @Qualifier("finVoucherModelHeadServiceCommon")
    private FinVoucherModelHeadService finVoucherModelHeadService;
    @Autowired
    @Qualifier("finVoucherHeadServiceCommon")
    private FinVoucherHeadService finVoucherHeadService;
    @Autowired
    @Qualifier("finVoucherBillRServiceCommon")
    private FinVoucherBillRService finVoucherBillRService;
    @Autowired
    @Qualifier("apPayHeadServiceCommon")
    private ApPayHeadService apPayHeadService;
    @Autowired
    private ApPayLineService apPayLineService;
    @Autowired
    private ApInvoiceMemoEcoService invoiceMemoEcoService;
    @Autowired
    private ApInvoiceMemoHeadMService apInvoiceMemoHeadMService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getApInvoiceMemoHeadList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2020-10-27 14:28:09
     * @author 
     * @param pages
     * @param apInvoiceMemoHeadCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getApInvoiceMemoHeadList")
    public String getApInvoiceMemoHeadList(Pages pages, ApInvoiceMemoHeadCO apInvoiceMemoHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        List<ApInvoiceMemoHead> apInvoiceMemoHeadList = this.apInvoiceMemoHeadService.getDataObjectsForDataAuth("", pages, apInvoiceMemoHeadCO);
        
        //付款来源类型
        Map paySourceTypeMap = DataBox.getApInvoiceMemoSourceType();
        //状态
        Map payStatusMap = RDDataBox.getStatusMap();
        //获取出纳状态
        Map paidStatusMap = DataBox.getPaidStatusMap();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //发票类型
        Map invoiceTypeMap = DataBox.getApInvoiceMemoType();
        
        //循环设置职员和组织信息
        for(ApInvoiceMemoHead apInvoiceMemoHead: apInvoiceMemoHeadList) {
            apInvoiceMemoHead.setStaffName(this.hrCommonService.getHrStaff(apInvoiceMemoHead.getStaffCode()).getStaffName());
            apInvoiceMemoHead.setDepartmentName(this.hrCommonService.getHrDepartment(apInvoiceMemoHead.getDepartmentCode()).getDepartmentName());
        }
        
        //页面属性设置
        model.addAttribute("payHeadList", apInvoiceMemoHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("paySourceTypeMap", paySourceTypeMap);
        model.addAttribute("payStatusMap", payStatusMap);
        model.addAttribute("paidStatusMap", paidStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("invoiceTypeMap", invoiceTypeMap);
        //工作流属性
        this.setWorkflowModel(model, "AP");
        
        return "basic.jsp?content=apInvoiceMemo/apInvoiceMemoList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2020-10-27 14:28:09
     * @author 
     * @param apInvoiceMemoHead
     * @param model
     * @return String
     *
     */
    @RequestMapping("getApInvoiceMemoHead")
    public String getApInvoiceMemoHead(ApInvoiceMemoHeadBase apInvoiceMemoHead, Model model) {
        //查询要编辑的数据
        if(apInvoiceMemoHead!=null&&StringUtils.isNotBlank(apInvoiceMemoHead.getInvoiceHeadCode())) {
            
            //根据version请求参数，判断数据从原表获取还是变更表获取
            if(apInvoiceMemoHead.getVersion()!=null&&apInvoiceMemoHead.getVersion()>0) {
                ApInvoiceMemoHeadBase apInvoiceMemoHeadTemp = this.apInvoiceMemoHeadMService.getDataObject(apInvoiceMemoHead.getInvoiceHeadCode(), apInvoiceMemoHead.getVersion());
                if(apInvoiceMemoHeadTemp!=null) {
                    apInvoiceMemoHead = apInvoiceMemoHeadTemp;
                }
            }else {
                ApInvoiceMemoHeadBase apInvoiceMemoHeadTemp = this.apInvoiceMemoHeadService.getDataObject(apInvoiceMemoHead.getInvoiceHeadCode());
                if(apInvoiceMemoHeadTemp!=null) {
                    apInvoiceMemoHead = apInvoiceMemoHeadTemp;
                }
            }
            
            //设置显示字段
            apInvoiceMemoHead.setStaffName(this.hrCommonService.getHrStaff(apInvoiceMemoHead.getStaffCode()).getStaffName());
            apInvoiceMemoHead.setDepartmentName(this.hrCommonService.getHrDepartment(apInvoiceMemoHead.getDepartmentCode()).getDepartmentName());
            
            //获取采购订单信息
            if(apInvoiceMemoHead.getInvoiceSourceType().equals("PO_INVOICE")) {
                //获取原发票信息
                ApInvoiceHead apInvoiceHead = this.apInvoiceHeadService.getDataObject(apInvoiceMemoHead.getInvoiceSourceHeadCode());
                apInvoiceMemoHead.setSourceHeadAmount(apInvoiceHead.getAmount());
            }
            //获取收款人信息
            apInvoiceMemoHead.setReceiverName(this.masterDataCommonService.getVendorMap().get(apInvoiceMemoHead.getReceiver()));
            //获取银行信息
            apInvoiceMemoHead.setBankName(this.datasetCommonService.getBank().get(apInvoiceMemoHead.getBankCode()));
            //获取供应商相关信息
            try {
                MdVendor mdVendor = this.masterDataCommonService.getMdVendorInfoCache(apInvoiceMemoHead.getReceiver());
                apInvoiceMemoHead.setVendorAddress(mdVendor.getVendorAddress());
                apInvoiceMemoHead.setVendorContact(mdVendor.getMdVendorContactList().get(0).getContactName()+" "+mdVendor.getMdVendorContactList().get(0).getContactTelephone());
                apInvoiceMemoHead.setVendorLicenseNumber(mdVendor.getMdVendorLicense().getLicenseNumber());
            }catch(Exception e) {}
        }else {
            //新增通知单
            //从发票生成通知单的情况
            if(StringUtils.isNotBlank(apInvoiceMemoHead.getInvoiceSourceHeadCode())&&StringUtils.isNotBlank(apInvoiceMemoHead.getInvoiceType())) {
                //获取原发票信息
                ApInvoiceHead apInvoiceHead = this.apInvoiceHeadService.getDataObject(apInvoiceMemoHead.getInvoiceSourceHeadCode());
                //将发票信息复制到通知单
                apInvoiceMemoHead.setPayMode(apInvoiceHead.getPayMode());
                apInvoiceMemoHead.setBankAccount(apInvoiceHead.getBankAccount());
                apInvoiceMemoHead.setBankCode(apInvoiceHead.getBankCode());
                apInvoiceMemoHead.setBankName(this.datasetCommonService.getBank().get(apInvoiceMemoHead.getBankCode()));
                apInvoiceMemoHead.setSubBankCode(apInvoiceHead.getSubBankCode());
                apInvoiceMemoHead.setCurrencyCode(apInvoiceHead.getCurrencyCode());
                apInvoiceMemoHead.setInvoiceSourceType("PO_INVOICE");
                apInvoiceMemoHead.setPayer(apInvoiceHead.getPayer());
                apInvoiceMemoHead.setSourceHeadAmount(apInvoiceHead.getAmount());
                apInvoiceMemoHead.setReceiver(apInvoiceHead.getReceiver());
                apInvoiceMemoHead.setReceiverName(this.masterDataCommonService.getVendorMap().get(apInvoiceMemoHead.getReceiver()));
                //获取供应商相关信息
                try {
                    MdVendor mdVendor = this.masterDataCommonService.getMdVendorInfoCache(apInvoiceMemoHead.getReceiver());
                    apInvoiceMemoHead.setVendorAddress(mdVendor.getVendorAddress());
                    apInvoiceMemoHead.setVendorContact(mdVendor.getMdVendorContactList().get(0).getContactName()+" "+mdVendor.getMdVendorContactList().get(0).getContactTelephone());
                    apInvoiceMemoHead.setVendorLicenseNumber(mdVendor.getMdVendorLicense().getLicenseNumber());
                }catch(Exception e) {}
            }
            
            //初始化默认字段
            //payHead.setAmount(0D);
            apInvoiceMemoHead.setPaidStatus("N");
            apInvoiceMemoHead.setStatus("NEW");
            
            //获取当前用户职员信息
            HrStaffInfoRO staffInfo = this.hrCommonService.getStaffInfo(ShiroUtil.getPrincipal());
            apInvoiceMemoHead.setStaffCode(staffInfo.getStaffCode());
            apInvoiceMemoHead.setDepartmentCode(staffInfo.getDepartmentCode());
            apInvoiceMemoHead.setStaffName(staffInfo.getStaffName());
            apInvoiceMemoHead.setDepartmentName(staffInfo.getDepartmentName());
        }
        
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //付款来源类型
        Map paySourceTypeMap = DataBox.getApInvoiceMemoSourceType();
        //状态
        Map payStatusMap = RDDataBox.getStatusMap();
        //获取出纳状态
        Map paidStatusMap = DataBox.getPaidStatusMap();
        //获取付款方式
        Map payModeMap = this.datasetCommonService.getPayMode();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //获取本公司
        Map vendorOwnMap = this.masterDataCommonService.getOwnCustomerMap();
        //审批状态
        Map approveStatusMap = RDDataBox.getApproveStatusMap();
        //发票类型
        Map invoiceTypeMap = DataBox.getApInvoiceMemoType();
        
        //页面属性设置
        model.addAttribute("payHead", apInvoiceMemoHead);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("paySourceTypeMap", paySourceTypeMap);
        model.addAttribute("payStatusMap", payStatusMap);
        model.addAttribute("paidStatusMap", paidStatusMap);
        model.addAttribute("payModeMap", payModeMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("vendorOwnMap", vendorOwnMap);
        model.addAttribute("approveStatusMap", approveStatusMap);
        model.addAttribute("invoiceTypeMap", invoiceTypeMap);
        //工作流属性
        this.setWorkflowModel(model, "AP", apInvoiceMemoHead.getInvoiceHeadCode());
        
        return "basic.jsp?content=apInvoiceMemo/apInvoiceMemoEdit";
    }
    
    
    
    /**
     * 
     * @description 获取采购订单选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectPOModal")
    public String getSelectPOModal(Pages pages, PoHeadCO poHeadCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分页查询数据
        poHeadCO.setStatus("CONFIRM");
        poHeadCO.setApproveStatus("APPROVE");
        List<PoHead> poHeadList = this.poHeadService.getDataObjects(pages, poHeadCO);
        
        //采购订单类型
        Map poTypeMap = this.datasetCommonService.getPOType();
        //状态
        Map poStatusMap = com.erp.order.po.dao.data.DataBox.getPoStatusMap();
        //获取供应商
        Map vendorMap = this.masterDataCommonService.getVendorMap();
        //获取项目
        Map projectMap = this.masterDataCommonService.getProjectMap();
        
        //循环设置职员和组织信息
        for(PoHead poHead: poHeadList) {
            poHead.setStaffName(this.hrCommonService.getHrStaff(poHead.getStaffCode()).getStaffName());
            poHead.setDepartmentName(this.hrCommonService.getHrDepartment(poHead.getDepartmentCode()).getDepartmentName());
        }
        
        //页面属性设置
        model.addAttribute("poHeadList", poHeadList);
        model.addAttribute("pages", pages);
        model.addAttribute("poTypeMap", poTypeMap);
        model.addAttribute("poStatusMap", poStatusMap);
        model.addAttribute("vendorMap", vendorMap);
        model.addAttribute("projectMap", projectMap);
        
        return "apInvoiceMemo/pop/selectPOModal";
    }
    
    
    
    /**
     * 
     * @description 获取收款方对应的银行选择框
     * @date 2020年7月20日
     * @author dongbin
     * @return
     * @return String
     *
     */
    @RequestMapping("getSelectBankModal")
    public String getSelectBankModal(Pages pages, MdVendorBankCO mdVendorBankCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        pages.setMax(100);
        
        //分页查询数据
        List<MdVendorBank> mdCustomerBankList = this.mdVendorBankService.getBankListByVendorCode(pages, mdVendorBankCO);
        
        //获取银行
        Map bankMap = this.datasetCommonService.getBank();
        
        
        //页面属性设置
        model.addAttribute("mdCustomerBankList", mdCustomerBankList);
        model.addAttribute("pages", pages);
        model.addAttribute("bankMap", bankMap);
        
        return "apInvoiceMemo/pop/selectBankModal";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2020-10-27 14:28:09
     * @author 
     * @param apInvoiceMemoHead
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editApInvoiceMemoHead")
    public String editApInvoiceMemoHead(@Valid ApInvoiceMemoHead apInvoiceMemoHead, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getApInvoiceMemoHead";
        }
        
        try {
            //对当前编辑的对象初始化默认的字段
            
            //保存编辑的数据
            this.apInvoiceMemoHeadService.insertOrUpdateDataObject(apInvoiceMemoHead);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", apInvoiceMemoHead.getInvoiceHeadCode());
        }catch(Exception e){
            if(e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "通知单编码已存在请重新输入");
                attr.addAttribute("apType", "Invoice");
                return "redirect:/web/apInvoiceHead/getApInvoiceHeadList";
            }else {
                throw e;
            }
        }
        
        return "redirect:getApInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2020-10-27 14:28:09
     * @author 
     * @param apInvoiceMemoHead
     * @return String
     *
     */
    @RequestMapping("deleteApInvoiceMemoHead")
    public String deleteApInvoiceMemoHead(ApInvoiceMemoHead apInvoiceMemoHead, RedirectAttributes attr) {
        //删除数据前验证数据
        if(apInvoiceMemoHead!=null&&apInvoiceMemoHead.getInvoiceHeadId()!=null) {
            if(apInvoiceMemoHead.getStatus().equals("NEW")) {
                //删除数据
                this.apInvoiceMemoHeadService.deleteDataObject(apInvoiceMemoHead);
                
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }else {
                //提示信息
                attr.addFlashAttribute("hint", "hint");
                attr.addFlashAttribute("alertMessage", "非新建状态的通知单不能删除");
            }
        }
        
        return "redirect:getApInvoiceMemoHeadList";
    }
    
    
    
    /**
     * 
     * @description 更新审批状态
     * @date 2020年8月4日
     * @author dongbin
     * @param code
     * @param approveStatus
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateApproveStatus")
    public String updateApproveStatus(String code, String invoiceSourceHeadCode, String approveStatus, RedirectAttributes attr) {
        
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(approveStatus)) {
            if(approveStatus.equals("UNSUBMIT")) {
                boolean payFlag = this.apPayHeadService.isExistApPayRelateApInvoice(invoiceSourceHeadCode);
                if(payFlag) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前关联的发票已付款核销不能变更");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getApInvoiceMemoHead";
                }
                
                //ECO===记录变更历史数据
                int errorCode = this.invoiceMemoEcoService.saveModifyHistory(code);
                if(errorCode!=0) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前采购发票保存变更历史错误，无法变更");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getApInvoiceMemoHead";
                }
            }
            
            //更新审核状态
            this.apInvoiceMemoHeadService.updateApproveStatus(code, approveStatus);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "提交或审批数据错误");
            attr.addAttribute("invoiceHeadCode", code);
        }
        
        return "redirect:getApInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 更新数据状态
     * @date 2020年10月24日
     * @author dongbin
     * @param code
     * @param status
     * @param attr
     * @return
     * @return String
     *
     */
    @RequestMapping("updateDataStatus")
    public String updateDataStatus(String code, String invoiceSourceHeadCode, String status, RedirectAttributes attr) {
        if(StringUtils.isNotBlank(code)&&StringUtils.isNotBlank(status)) {
            if(status.equals("CANCEL")) {
                boolean payFlag = this.apPayHeadService.isExistApPayRelateApInvoice(invoiceSourceHeadCode);
                if(payFlag) {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "当前关联的发票已付款核销不能取消");
                    attr.addAttribute("invoiceHeadCode", code);
                    return "redirect:getApInvoiceMemoHead";
                }
            }
            
            //更新审核状态
            this.apInvoiceMemoHeadService.updateDataStatus(code, status);
            //提示信息
            attr.addFlashAttribute("hint", "success");
            attr.addAttribute("invoiceHeadCode", code);
        }else {
            //提示信息
            attr.addFlashAttribute("hint", "hint");
            attr.addFlashAttribute("alertMessage", "修改数据状态错误");
            attr.addAttribute("invoiceHeadCode", code);
        }
        
        return "redirect:getApInvoiceMemoHead";
    }
    
    
    
    /**
     * 
     * @description 自动创建凭证分录
     * @date 2020年9月25日
     * @author dongbin
     * @param headCode
     * @return
     * @return String
     *
     */
    @RequestMapping("autoCreateVoucherEntry")
    @ResponseBody
    public String autoCreateVoucherEntry(String headCode, String invoiceType){
        try {
            //转换入库类型为单据类型
            String billType = com.erp.common.voucher.dao.data.DataBox.getVoucherTypeByBusinessType(invoiceType);
            
            //删除自动生成的凭证和分录
            //根据单据头code获取凭证头code
            String voucherHeadCode = this.finVoucherBillRService.getVoucherHeadCodeByBillHeadCode(billType, headCode);
            //删除凭证
            if(StringUtils.isNotBlank(voucherHeadCode)) {
                this.finVoucherHeadService.deleteFinVoucherHeadByVoucherHeadCode(voucherHeadCode);
            }
            
            //自动生成凭证和分录
            //计算分录的金额
            //获取行
            List<ApInvoiceMemoLine> lineList = this.apInvoiceMemoLineService.getApInvoiceMemoLineListByHeadCode(headCode);
            
            BigDecimal voucherAmount = new BigDecimal(0D);
            BigDecimal amountSum = new BigDecimal(0D);
            BigDecimal taxAmountSum = new BigDecimal(0D);
            //循环获取加和
            for(ApInvoiceMemoLine line: lineList) {
                BigDecimal amount = line.getAmount();
                BigDecimal taxAmount = line.getTaxAmount();
                //计算合计金额
                amountSum = amountSum.add(amount);
                taxAmountSum = taxAmountSum.add(taxAmount);
                voucherAmount = voucherAmount.add(amount).add(taxAmount);
            }
            
            //调用自动创建方法
            this.finVoucherModelHeadService.autoCreateVoucher(headCode, new Double[]{Math.abs(amountSum.doubleValue()),Math.abs(taxAmountSum.doubleValue()),Math.abs(voucherAmount.doubleValue())}, billType);
            
            return JsonDataUtil.getExecuteJson(0);
        }catch(Exception e) {
            return JsonDataUtil.getExecuteJson(-1, "重新生成分录错误");
        }
    }
}
